import { useForm } from '@formily/react';
import { getMessage } from '@inbiz/react';
import { Select } from 'antd';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getStaticDataList } from '../webServer/services';

type Iprops = {
  value: string[];
  dataList: { label: string; value: string }[];
  groupId: string | { groupId: string };
  onChange?: Function;
  mode?: 'multiple' | 'tags' | undefined | 'custom';
};
const StaticData = (props: Iprops) => {
  const { value, mode, groupId } = props;
  const [val, $val] = useState(value || []);
  const [dataList, $dataList] = useState([]);

  const beforeGroupId: any = useRef<any>(undefined);

  const beforeMode: any = useRef<any>(undefined);

  const info: any = useForm();
  let appId = useMemo(() => {
    return info.appInfo.appId;
  }, [info]);

  const onChange = useCallback(
    (e) => {
      $val(e);
      props.onChange && props.onChange(e);
    },
    [props],
  );

  const getData = useCallback(() => {
    if (groupId && groupId != '{{$deps[0]}') {
      if (typeof groupId == 'string') {
        getDataList(groupId);
      } else if (typeof groupId == 'object' && groupId.groupId) {
      }
      getDataList(groupId?.groupId);
    }
  }, [groupId]);

  //获取静态数据源
  const getDataList = (groupId: string | number) => {
    if (groupId) {
      getStaticDataList({ appId, groupKey: groupId }).then((res) => {
        if (res && res.length) {
          const data = res.map((item: any) => {
            return {
              label: getMessage(item.Text),
              value: item.Value,
            };
          });
          $dataList(data);
        }
      });
    }
  };
  useEffect(() => {
    // 这里的类型判断是为了兼容老数据
    if (typeof groupId == 'string' && beforeGroupId?.current && beforeGroupId.current !== groupId) {
      props.onChange && props.onChange([]);
      $val((origin) => []);
    }
    beforeGroupId.current = groupId;
  }, [groupId]);

  useEffect(() => {
    if (beforeMode?.current && beforeMode.current !== mode) {
      props.onChange && props.onChange([]);
      $val((origin) => []);
    }
    beforeMode.current = mode;
  }, [mode]);

  useEffect(() => {
    getData();
  }, [groupId]);
  return (
    <Select
      options={dataList}
      mode={mode == 'custom' ? 'multiple' : mode}
      onChange={onChange}
      value={val}
      allowClear
      // onFocus={getData}
    />
  );
};
export default StaticData;
